package com.hgyc.mom.tool.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hgyc.mom.common.constant.ScheduleConstants;
import com.hgyc.mom.common.exception.job.TaskException;
import com.hgyc.mom.tool.entity.Job;
import com.hgyc.mom.tool.mapper.JobMapper;
import com.hgyc.mom.tool.service.JobService;
import com.hgyc.mom.tool.util.ScheduleUtils;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 定时任务调度Service业务层实现
 *
 * @author fwj
 * @since 2025-05-08
 */
@Slf4j
@Service("jobService")
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements JobService {

    @Autowired
    private Scheduler scheduler;

    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException
    {
        scheduler.clear();
        List<Job> jobList = list();
        log.info("---------------启动定时任务开始---------------");
        for (Job job : jobList)
        {
            log.info("任务名：{}， 执行类：{}, 执行周期：{}", job.getJobName(), job.getInvokeTarget(), job.getCronExpression());
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        log.info("---------------启动定时任务结束---------------");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run(Job job) throws SchedulerException {
        Long jobId = job.getId();
        String jobGroup = job.getJobGroup();
        Job properties = getById(jobId);
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap);
    }

    @Override
    public void test() {
        log.info("执行一次定时任务");
    }
}